package com.credit.mola.app.ui.credit.activity

import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.credit.mola.app.R
import com.credit.mola.app.databinding.CreditMainBinding
import com.credit.mola.app.pro.ProActivity
import com.credit.mola.app.status.StatusRepository
import com.credit.mola.app.ui.credit.page.CreditCommonPage
import com.credit.mola.app.ui.credit.page.LimitPage
import com.credit.mola.app.ui.credit.page.RepayPage
import com.credit.mola.app.ui.user.activity.MobileCheckActivity
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.dialog.VersionUpdateDialog
import com.credit.mola.app.utils.helper.ActivityStackHelper
import com.credit.mola.app.utils.helper.CmVersionUpdateHelper
import com.credit.mola.app.utils.helper.CustomConfigHelper
import com.credit.mola.app.utils.helper.ForegroundBackgroundHelper
import com.credit.mola.app.utils.helper.ForegroundBackgroundObserver
import com.credit.mola.app.utils.helper.SikadwaMainProcessHelper
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.AppUrls.addCommonParams
import com.credit.mola.app.utils.http.IHttpCallback
import com.credit.mola.app.utils.log.HHLog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.util.Calendar
import java.util.TimeZone

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/21 19:28
 * @Annotation：贷款主页
 */
class CreditActivity: ProActivity() {
    lateinit var binding: CreditMainBinding

    //贷款额度
    private var mLimitPage: LimitPage? = null
    //贷款还款
    private var mRepayPage: RepayPage? = null
    //贷款 通用状态列表，包含：审核中、拒绝、放贷中、放贷中法语
    private var mCommonPage: CreditCommonPage? = null

    private var updateHelper: CmVersionUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {

        } else {

        }
    }

    override fun getRootView(): View {
        binding = CreditMainBinding.inflate(layoutInflater)
        return binding.root
    }

    @Subscribe
    override fun initView() {
        setBackExit(true)
        setExitTips(getString(R.string.exit_tips))

        EventBus.getDefault().register(this)
        ForegroundBackgroundHelper.addObserve(onForegroundBackgroundObserver)
    }

    override fun initListener() {
    }

    override fun initData() {
        //保存时区id, 用于切换切换时区之后进入应用调接口报错问题,此值在启动页使用
        Configs.saveSPString(Configs.SPKEY.SIKADWA_TIMEZONE_ID, TimeZone.getDefault().id)

        showLoading()
        loadProcessAction()

        //是否有新版本
        val isUpdate = CustomConfigHelper.isCmVersionUpdate()
        if (isUpdate){
            showCmVersionUpdateDialog()
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshProcess(event: String){
        when(event){
            Configs.Event.PROCESS_REFRESH -> {//刷新
                loadProcessAction()
            }
            Configs.Event.CM_VERSION_UPDATE -> {//版本更新
                startCmVersionUpdateNow()
            }
        }
    }

    /**
     * 显示贷款额度页面
     */
    fun showLimitPage(isComplete: Boolean){
        hideAllPage()
        if (mLimitPage == null) {
            mLimitPage = LimitPage(isComplete)
        }
        mLimitPage?.let {
            if (it.isAdded) {
                showContainerFragement(it)
                it.isComplete = isComplete
                it.showStateView()
            } else {
                addContainerFragement(R.id.containerLayout, it)
            }
        }
    }

    /**
     * 显示待还款页面
     */
    fun showRepayPage() {
        hideAllPage()
        if (mRepayPage == null) {
            mRepayPage = RepayPage()
        }
        mRepayPage?.let {
            if (it.isAdded) {
                showContainerFragement(it)
                it.refreshAction()
            } else {
                addContainerFragement(R.id.containerLayout, it)
            }
        }
    }

    /**
     * 显示审核中、放款中、拒绝公用一个页面
     */
    fun showCommonPage(data: JSONObject) {
        hideAllPage()
        if (mCommonPage == null) {
            mCommonPage = CreditCommonPage(data)
        }
        mCommonPage?.let {
            if (it.isAdded) {
                showContainerFragement(it)
                it.refreshView(data)
            } else {
                addContainerFragement(R.id.containerLayout, it)
            }
        }
    }

    /**
     * 校验手机号
     */
    fun showCreditMolaMobileCheckAction(){
        //当前栈顶是 手机号校验页面 不重复跳转
        if (ActivityStackHelper.isCurrentActivity(MobileCheckActivity::class.java)){
            return
        }
        //是否是审核账号
        val isConfigAccount = Configs.getSPBoolean(Configs.SPKEY.SIKADWA_IS_CONFIG_ACCOUNT)
        if(isConfigAccount) {//审核账号，直接不走校验
            return
        }
        MobileCheckActivity.start(this)
    }

    /**
     * 隐藏所有的页面
     */
    private fun hideAllPage() {
        mLimitPage?.let {
            hideContainerFragement(mLimitPage)
        }
        mRepayPage?.let {
            hideContainerFragement(mRepayPage)
        }
        mCommonPage?.let {
            hideContainerFragement(mCommonPage)
        }
    }

    /**
     * 版本更新Dialog
     */
    private fun showCmVersionUpdateDialog(){
        val lastTime = Configs.getSPString(Configs.SPKEY.CREDIT_MOLA_VERSION_SHOW_LASTTIME)
        if (lastTime.isNotEmpty() && isSameDay(lastTime.toLong(),System.currentTimeMillis())){
            return
        }
        Configs.saveSPString(Configs.SPKEY.CREDIT_MOLA_VERSION_SHOW_LASTTIME,"${System.currentTimeMillis()}")
        val versionUpdateDialog = VersionUpdateDialog(this,"Home page",object : VersionUpdateDialog.IDialogCallback{
            override fun onUpdateNowClick() {
                startCmVersionUpdateNow()
            }
        })
        versionUpdateDialog.show()
    }

    /**
     * 启动版本更新
     */
    private fun startCmVersionUpdateNow(){
        try {
            if (updateHelper == null){
                updateHelper = CmVersionUpdateHelper(this@CreditActivity, true, updateLauncher)
            }
            updateHelper?.checkVersionUpdate {  }
        } catch (e: Exception) {
        }
    }

    /**
     * 获取流程
     */
    private fun loadProcessAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.PROCESS)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存用户流程状态
                obj?.let {
//                    val allStepTitles = obj.optJSONArray("allStepTitles")
//                    allStepTitles.put("Account Info")
//                    allStepTitles.put("Ocr Info")
//                    allStepTitles.put("Face recognition")
//                    val allSteps = obj.optJSONArray("allSteps")
//                    allSteps.put("account_info")
//                    allSteps.put("ocr_info")
//                    allSteps.put("sefie_info")
//                    val steps = obj.optJSONArray("steps")
//                    steps.put("account_info")
//                    steps.put("sefie_info")
//                    steps.put("ocr_info")
//                    val index = Random.nextInt(3)
//                    when(index){
//                        0 -> {
//                            steps.put("ocr_info")
//                        }
//                        1 -> {
//                            steps.put("sefie_info")
//                        }
//                        else -> {
//                            steps.put("account_info")
//                        }
//                    }
                    SikadwaMainProcessHelper.saveSikadwaMainProcessData(it)
                    //通知全局流程刷新完成
                    EventBus.getDefault().post(Configs.Event.PROCESS_REFRESHED)

                    // TODO: 根据 smsFlag 或 whatsappFlag 判断是否需要校验手机号
                    if (SikadwaMainProcessHelper.isSikadwaMainAuthCheckMobile()){//需要校验手机号
                        showCreditMolaMobileCheckAction()
                    }

                    //1、判断是否存在 订单状态
                    if (it.has("orderStatus")){
                        val orderStatus = it.optString("orderStatus")
                        //待还款
                        if (StatusRepository(null,orderStatus).isRepayNow()){
                            showRepayPage()
                            return
                        }
                        //放款中
                        if (StatusRepository(null,orderStatus).isDisbursing()){
                            it.put("eventRemark","CreditAudit Page")
                            showCommonPage(it)
                            return
                        }
                        //申请贷款被拒绝
                        if (StatusRepository(null,orderStatus).isRejected()){
                            it.put("eventRemark","CreditApplyFailed Page")
                            showCommonPage(it)
                            return
                        }
                    }

                    //2、判断是否存在 贷款申请状态
                    if (it.has("applyStatus")){
                        val applyStatus = it.optString("applyStatus")
                        //审核中
                        if (StatusRepository(applyStatus).isReviewing()){
                            it.put("eventRemark","CreditAudit Page")
                            showCommonPage(it)
                            return
                        }
                        //被拒绝
                        if (StatusRepository(applyStatus).isRejected()){
                            it.put("eventRemark","CreditApplyFailed Page")
                            showCommonPage(it)
                            return
                        }
                    }

                    //3、直接显示贷款额度页面
                    val stepsArray = it.optJSONArray("steps")
                    stepsArray?.let { array ->
                        showLimitPage(array.length() == 0)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    /**
     * 前后台切换监听
     */
    private val onForegroundBackgroundObserver = object : ForegroundBackgroundObserver {
        override fun foregroundBackgroundNotify(isForeground: Boolean) {
            HHLog.e("Main background>>>>>>>>>$isForeground")
            //从桌面进入前台，需要刷新总流程
//            if (isForeground) {
//                loadProcessAction()
//            }
        }
    }

    /**
     * 两个时间戳是否为同一天
     * @param timestamp1
     * @param timestamp2
     * @return
     */
    fun isSameDay(timestamp1: Long, timestamp2: Long): Boolean {
        val cal1 = Calendar.getInstance()
        cal1.setTimeInMillis(timestamp1)
        val cal2 = Calendar.getInstance()
        cal2.setTimeInMillis(timestamp2)
        return cal1[Calendar.YEAR] == cal2[Calendar.YEAR] && cal1[Calendar.MONTH] == cal2[Calendar.MONTH] && cal1[Calendar.DAY_OF_MONTH] == cal2[Calendar.DAY_OF_MONTH]
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.onResumeInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        ForegroundBackgroundHelper.removeObserver(onForegroundBackgroundObserver)
    }
}